<?php

declare(strict_types=1);

namespace App\Job;

use App\Model\PointPosition;
use App\Model\PositionPaper;
use App\Model\PositionSupervise;
use App\Model\PositionSuperviseSheet;
use Hyperf\AsyncQueue\Job;
use Hyperf\DbConnection\Db;

class PositionStaticJob extends Job
{
    public $params;

    protected $maxAttempts = 2;

    public function __construct($params)
    {
        $this->params = $params;
    }

    public function handle()
    {
        $header_data=[
            '点位名称',
            '所属分类',
            '所属区县',
            '责任单位',
            '被监督次数',
            '合格次数',
            '不合格次数',
            '平均分',
            '总得分'
        ];
        $file = $this->params['file_url'];
        $start_time = isset($this->params['start_time'])?$this->params['start_time']:'';
        $end_time = isset($this->params['end_time'])?$this->params['end_time']:'';
        $folder = BASE_PATH.'/public'.$file;
        $fp = fopen($folder,'w+');
        if (!empty($header_data)) {
            foreach ($header_data as $key => $value) {
                $header_data[$key] = iconv('utf-8', 'GBK', $value);
            }
            fputcsv($fp, $header_data);
        }
        $query = PointPosition::query()->orderBy('id','desc')->join('position_supervise',function($join){
            $join->on('position_supervise.position_id','=','point_position.id')
                ->whereNull('position_supervise.deleted_at');
        })->with(['mainunit','category','district']);
        $query_count = clone $query;
        $all = $query_count->count(DB::raw('DISTINCT(cc_point_position.id)'));
        $start_count=0;
        $category_score=[];
        $query->select(DB::raw('DISTINCT cc_point_position.*'))->chunk(300,function($positions) use($fp,$all,$start_time,$end_time,&$start_count,&$category_score){
            foreach ($positions as $position){
                if(isset($category_score[$position->category_id])){
                    $position->paper_all_score = $category_score[$position->category_id];
                }else{
                    $all_score = PositionPaper::query()->where('category_id',$position->category_id)->sum('score');
                    $category_score[$position->category_id]=$all_score;
                    $position->paper_all_score = $all_score;
                }
                //$row[0] = $user->mobile.' ';
                $row[0] = iconv('utf-8', 'GBK//TRANSLIT//IGNORE',$position->name);
                $row[1] = iconv('utf-8', 'GBK//TRANSLIT//IGNORE',object_get($position,'category.name','暂无'));
                $row[2] = iconv('utf-8', 'GBK//TRANSLIT//IGNORE',object_get($position,'district.name','暂无'));
                $row[3] = iconv('utf-8', 'GBK//TRANSLIT//IGNORE',object_get($position,'mainunit.name','暂无'));

                $query_all = PositionSupervise::query()->where('position_id',$position->id);
                $query_score = PositionSupervise::query()->where('position_id',$position->id);
                $query_below = PositionSuperviseSheet::query()->join('position_supervise',function($join) use($position){
                    $join->on('position_supervise_sheet.supervise_id','=','position_supervise.id')
                        ->where('position_id',$position->id)
                        ->whereNull('position_supervise.deleted_at');
                })->where('score',0);
                if($start_time!=''&&$end_time!=''){
                    $query_all->where('created_at','>=',$start_time)->where('created_at','<=',$end_time);
                    $query_score->where('created_at','>=',$start_time)->where('created_at','<=',$end_time);
                    $query_below->where('position_supervise_sheet.created_at','>=',$start_time)->where('position_supervise_sheet.created_at','<=',$end_time);
                }
                $position->all_nums = $query_all->count('id');
                $position->below_nums = $query_below->count(DB::raw('DISTINCT(supervise_id)'));
                $position->qualified_nums = $position->all_nums-$position->below_nums;
                $position->all_score = $query_score->sum('final_score');
                $position->avg_score =  $position->all_nums?sprintf('%.2f',$position->all_score/$position->all_nums):0;
                $row[4]=$position->all_nums;
                $row[5]=$position->qualified_nums;
                $row[6]=$position->below_nums;
                $row[7]=$position->avg_score;
                $row[8]=$position->all_score;
                fputcsv($fp,$row);
            }
            $start_count+=300;
            $progress = $start_count>=$all?1:sprintf('%.2f',$start_count/$all);
            cache()->set('export_'.$this->params['hash_id'],$progress*100);

        });
    }
}
